package com.ziiwee.reduce.rest.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.ziiwee.reduce.commons.utils.ReflectUtil;

public class JsonUtil {

    public static ObjectMapper getObjectMapper() {
        try {
            return SpringUtil.getBean(ObjectMapper.class);
        } catch (Exception e) {
            return new ObjectMapper();
        }
    }

    public static <T> T read(String json, Class<T> type) {
        try {
            return getObjectMapper().readValue(json, type);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T readByRef(String json, TypeReference<T> valueTypeRef) {
        try {
            return getObjectMapper().readValue(json, valueTypeRef);
        } catch (Exception e) {
            return null;
        }
    }


    public static String write(Object object) {
        try {
            return getObjectMapper().writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Object castValue(Class<?> type, Object value) {
        try {
            Object o = ReflectUtil.castValue(type, value);
            if (o != null) {
                return o;
            }
            return getObjectMapper().readValue(value.toString(), type);
        } catch (Exception e) {
            return null;
        }
    }

    public static String translateSnakeCaseName(String name) {
        return new PropertyNamingStrategy.SnakeCaseStrategy().translate(name);
    }

}
